package com.kizitonwose.calendarview.ui;

import com.kizitonwose.calendarview.model.CalendarDay;
import com.kizitonwose.calendarview.model.CalendarMonth;
import com.kizitonwose.calendarview.uinterface.MonthHeaderFooterBinder;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;

import java.util.List;

public class MonthViewHolder {

    private CalendarAdapter adapter;
    private ComponentContainer rootLayout;
    private List<WeekHolder> weekHolders;
    private MonthHeaderFooterBinder<ViewContainer> monthHeaderBinder;
    private MonthHeaderFooterBinder<ViewContainer> monthFooterBinder;
    private ViewContainer headerContainer;
    private ViewContainer footerContainer;
    private CalendarMonth month;
    private Component headerComponent;
    private Component footerComponent;

    public MonthViewHolder(CalendarAdapter adapter,
                           ComponentContainer rootLayout,
                           List<WeekHolder> weekHolders,
                           MonthHeaderFooterBinder<ViewContainer> monthHeaderBinder,
                           MonthHeaderFooterBinder<ViewContainer> monthFooterBinder){

        this.adapter = adapter;
        this.rootLayout = rootLayout;
        this.weekHolders = weekHolders;
        this.monthHeaderBinder = monthHeaderBinder;
        this.monthFooterBinder = monthFooterBinder;

        headerComponent = rootLayout.findComponentById(adapter.headerViewId);
        footerComponent = rootLayout.findComponentById(adapter.footerViewId);

    }

    public void bindMonth(CalendarMonth month){
        this.month = month;
//        System.out.println("月份数据" + month.toString());

        if (headerComponent != null) {
            if (headerContainer == null && monthHeaderBinder != null) {
                headerContainer = monthHeaderBinder.create(headerComponent);
            }
            if (monthHeaderBinder != null) {
                monthHeaderBinder.bind(headerContainer, month);
            }
        }

        if (footerComponent != null) {
            if (footerContainer == null && monthFooterBinder != null) {
                footerContainer = monthFooterBinder.create(footerComponent);
            }
            if (monthFooterBinder != null) {
                monthFooterBinder.bind(footerContainer, month);
            }
        }

        List<List<CalendarDay>> weekDays = month.getWeekDays();
        for(int index = 0 ; index < weekHolders.size() ; index++){
            WeekHolder weekHolder = weekHolders.get(index);
            if(index < weekDays.size()){
                weekHolder.bindWeekView(weekDays.get(index));
            }else{
                weekHolder.bindWeekView(null);
            }
        }
    }

    public void reloadDay(CalendarDay day){
        for(WeekHolder weekHolder : weekHolders){
            weekHolder.reloadDay(day);
        }
    }

}
